﻿var url;
var currentRole;
var currentUser;
var helper = new Helper();
var isNewNonHR = true;
var isNewRole = true;

jQuery(function () {

    if (checkAuthenticate()) {
        getUserToGrid();
    }
    addfilter();
    setInterval(grid_refresh, 60000);
});

function grid_refresh() {
    jQuery('#dgProduct').datagrid('reload');
}

function addfilter() {
    jQuery('#dgProduct').datagrid('enableFilter', [
        {
            field: 'PercentSpecial',
            type: 'numberbox',
            op: ['equal', 'notequal', 'less', 'greater']
        },
        {
            field: 'StartDate',
            type: 'hidefilter'
        },
        {
            field: 'EndDate',
            type: 'hidefilter'
        },
        {
            field: 'Active',
            type: 'hidefilter'
        },
        {
            field: 'Id',
            type: 'hidefilter'
        }
    ]

    );
}
function checkAuthenticate() {

    var userCookie = jQuery.cookie("exportCookie")
    var user = jQuery.parseJSON(userCookie);
    var role = user.RoleString;
    if (role == "Sc") {
        alert("You don't have permission to access this page");
        window.location = "/pages/login.aspx";
        return false;
    }
    else {
        return true;
    }
    
}
function getUserToGrid() {
    jQuery('#dgProduct').datagrid({
        url: "/service/api.ashx?metdhodName=getAllSpecialPercent",
        onDblClickRow: function (index, fields, value) {
            editNonHR(fields);
            addfilter();
        }
    });
}
function editRole(currentRole) {
    isNewRole = false;
    if (currentRole == undefined) {
        currentRole = jQuery('#dgRole').datagrid('getSelected');
    }
    if (currentRole != undefined) {
        jQuery('#dlgRole').dialog('open').dialog('setTitle', 'แก้ไข Role');
        jQuery('#roleName').val(currentRole.Name);
        jQuery('#roleEnable').prop('checked', currentRole.IsActive);
    }
}

function openSearchProduct() {
    jQuery('#productSearch').dialog('open').dialog('setTitle', 'ค้นหาสินค้า');
}

function searchProduct() {
    var productMatno = jQuery('#searchProductMatNo').val();
    var productThaiName = jQuery('#searchProductNameThai').val();
    var productEngName = jQuery('#searchProductNameEng').val();

    if (productMatno != '' || productThaiName != '' || productEngName != '') {



        var Query = "productNo=" + productMatno + "&productName=" + productThaiName + "&productNameEng=" + productEngName;
        jQuery('#dlgProductSearch').datagrid({
            url: "/service/api.ashx?metdhodName=getAllProduct&" + Query,
            //loadFilter: pagerFilter,
            //onDblClickRow: function (index, fields, value) {
            //    editNonHR(fields);
            //}
        });
    }
    else {
        alert('กรุณาเลือกเงื่อนไขในการค้นหาสินค้า');
    }
}

function addNonHR() {
    isNewNonHR = true;
    jQuery('#openSearchPopup').show();
    clearAllInput();
    jQuery('#dlgNonHr').dialog('open').dialog('setTitle', 'เพิ่ม % พิเศษรายสินค้า');
}

function addRole() {
    jQuery('#dlgRole').dialog('open').dialog('setTitle', 'เพิ่มระดับการใช้งาน');
}

var updateProductNo;
function editNonHR(editUser) {

    if (editUser == undefined || editUser == null) {
        editUser = jQuery('#dgProduct').datagrid('getSelected')
    }

    if (editUser == undefined || editUser == null) {
        return false;
    }
    else {
        isNewNonHR = false;
        jQuery('#openSearchPopup').hide();
        updateProductNo = editUser.Id;
        jQuery('#dlgNonHr').dialog('open').dialog('setTitle', 'แก้ไข % รายสินค้า');
        bindUser(editUser);
    }
}

function deleteNonHR() {
    jQuery.messager.confirm('ต้องการจะลบ % พิเศษ?', 'ลบข้อมูล % พิเศษ', function (r) {
        if (r) {
            var product = jQuery('#dgProduct').datagrid('getSelected');
            if (product == null || product == undefined) {
                alert("กรุณาเลือกสินค้าที่ต้องการลบ % พิเศษ");
                return;
            }
            jQuery.post('/service/api.ashx?metdhodName=deleteSpecialPercent&producId=' + product.Id, {
            }, function (result) {
                jQuery('#dgProduct').datagrid('reload');
                alert(result);
            }, 'text');
        }
    });
}

function deleteRole() {

    jQuery.messager.confirm('ต้องการจะลบ Role?', 'ข้อมูลพนักงานที่ใช้สิทธิ์ role นี้อยู่จะโดนลบไปด้วย ', function (r) {
        if (r) {
            var role = jQuery('#dgRole').datagrid('getSelected');
            jQuery.post('/service/api.ashx?metdhodName=deleteRole', {
                roleid: role.Id
            }, function (result) {
                jQuery('#dgRole').datagrid('reload');
                alert(result);
            }, 'text');
        }
    });

}



function validateRole(roleName, roleActive) {
    if (roleName == null || roleName == undefined || roleName == "") {
        alert("กรุณาระบุชื่อ Role");
        return false;
    }
    else if (roleActive == null || roleActive == undefined) {
        alert("กรุณาระบุสถานะ Role");
        return false;
    }
    return true;
}

//function pagerFilter(data) {
//    if (typeof data.length == 'number' && typeof data.splice == 'function') {	// is array
//        data = {
//            total: data.length,
//            rows: data
//        };
//    }
//    var dg = jQuery(this);
//    var opts = dg.datagrid('options');
//    var pager = dg.datagrid('getPager');
//    pager.pagination({
//        onSelectPage: function (pageNum, pageSize) {
//            opts.pageNumber = pageNum;
//            opts.pageSize = pageSize;
//            pager.pagination('refresh', {
//                pageNumber: pageNum,
//                pageSize: pageSize
//            });
//            dg.datagrid('loadData', data);
//        }
//    });
//    if (!data.originalRows) {
//        data.originalRows = (data.rows);
//    }
//    var start = (opts.pageNumber - 1) * parseInt(opts.pageSize);
//    var end = start + parseInt(opts.pageSize);
//    data.rows = (data.originalRows.slice(start, end));
//    return data;
//}

function formatDate(val, row) {
    if (val === null || val === '') {
        return null;
    }
    else {
        var d = new Date(parseInt(val.substr(6)));
        return jQuery.datepicker.formatDate('dd-MM-yy', d) + " " + d.getHours() + ":" + d.getMinutes() + ":" + d.getSeconds();
    }
}

function formatIsExpire(val, row) {
    if (row.EndDate === null || row.EndDate === '') {
        return null;
    }
    else {
        var d = new Date(parseInt(row.EndDate.substr(6)));
        var startdate = new Date();
        if (d < startdate) {
            return '<div class="ui-icon ui-icon-check" style="color:red;">Expired</div>';
        }
        else {
            return '<div class="ui-icon ui-icon-check" style="">Apply</div>';
        }
    }
}

function formatCheckbox(val, row) {
    if (row.IsActive === null || row.IsActive === '') {
        return '<div class="ui-icon ui-icon-check" style="">false</div>';
    }
    else {
        if (row.IsActive) {
            return '<div class="ui-icon ui-icon-check" style="">true</div>';
        }
        else {
            return '<div class="ui-icon ui-icon-check" style="">false</div>';
        }
    }
}

function searchUser() {
    var keyword = jQuery('#searcKeyword').val();
    var searchType = jQuery('#searchType').combobox('getValue');
    jQuery('#dg').datagrid({
        url: "/service/api.ashx?metdhodName=getalluserrole&keyword=" + escape(keyword) + "&searchType=" + searchType,
        loadFilter: pagerFilter,
        onDblClickRow: function (index, fields, value) {

            currentUser = fields.UserName;
            currentRole = fields.RoleName;
            editRole(fields);
        }
    });
}

function bindUser(user) {
    jQuery('#productNo').val(user.ProductCode);
    jQuery('#productName').val(user.ProductName);
    jQuery('#specialPercent').val(user.PercentSpecial);
    jQuery('#startdate').datebox('setValue', jQuery.datepicker.formatDate('mm/dd/yy', new Date(parseInt(user.StartDate.substr(6)))));
    jQuery('#enddate').datebox('setValue', jQuery.datepicker.formatDate('mm/dd/yy', new Date(parseInt(user.EndDate.substr(6)))));
    jQuery('#isactive').prop('checked',user.IsActive);

}

function selectProduct() {

    var productSelect = jQuery("#dlgProductSearch").datagrid("getSelected");
    jQuery("#productNo").val(productSelect.mmatno);
    jQuery("#productName").val(productSelect.mmatthai);
    jQuery('#productSearch').dialog('close')
}


function saveProduct() {
    var d = getAllInput();
    if (validateProduct(d)) {
        if (d[0].isactive == "on") {
            d[0].isactive = true;
        }

        if (isNewNonHR == undefined || isNewNonHR == true) {
            d[0]["isInsert"] = "true";
        }
        else {
            d[0]["isInsert"] = "false";
        }

        if (updateProductNo != undefined) {
            d[0]["Id"] = updateProductNo;
        }

        jQuery.post('/service/api.ashx?metdhodName=saveProductSpecial', {
            data: d,
        }, function (result) {
            getUserToGrid();
            alert(result);
            jQuery('#dlgNonHr').dialog('close');
            updateProductNo = undefined;
            addfilter();
        }, 'text');

        clearAllInput();

    }
}

function validateProduct(data) {
    data = data[0];
    if (data.productNo == null || data.productNo == undefined || data.productNo == "") {
        alert("กรุณาระบุ รหัสสินค้า 18 หลัก");
        return false;
    }
    else if (data.specialPercent == null || data.specialPercent == undefined || data.specialPercent == "") {
        alert("กรุณาระบุ % พิเศษ");
        return false;
    }
    else if (!jQuery.isNumeric(data.specialPercent)) {
        alert("กรุณาระบุ % พิเศษเป็นตัวเลข");
        return false;
    }
    else if (data.startdate == null || data.startdate == undefined || data.startdate == "") {
        alert("กรุณาระบุวันที่เริ่ม");
        return false;
    }
    else if (data.enddate == null || data.enddate == undefined || data.enddate == "") {
        alert("กรุณาระบุวันที่สิ้นสุด");
        return false;
    }
    else if (data.startdate != "" && data.enddate != "") {
        var std = jQuery.datepicker.parseDate('mm/dd/yy', data.startdate);
        var end = jQuery.datepicker.parseDate('mm/dd/yy', data.enddate);
        if (end < std) {
            alert("กรุณาระบุวันที่สิ้นสุดมากกว่าหรือเท่ากับวันที่เริ่มต้น");
            return false;
        }
    }

    return true;
}

function getAllInput() {
    var datas = [];
    var data = {};
    jQuery("form#FormNonHr :input").each(function () {
        var input = jQuery(this); // This is the jquery object of the input, do what you will
        var name = jQuery(input).attr("name");
        var type = jQuery(input).attr("type");

        if (type == 'checkbox') {
            var value;
            value = input.prop('checked');
            data[name] = value;
        }
        else if (name != undefined) {
            var value;
            value = input.val();
            data[name] = value;
        }
    });
    datas.push(data);
    return datas;
}


function clearAllInput() {

    jQuery("form#FormNonHr :input").each(function () {
        var input = jQuery(this); // This is the jquery object of the input, do what you will
        input.val('');
        return true;
    });
}